package com.xm.permission;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.accessibilityservice.GestureDescription;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import java.util.List;
import android.graphics.Path;

public class AutoStartAccessibilityService extends AccessibilityService {
    private static final String TAG = "AutoStartAccessibility";
    private static String TARGET_APP_PACKAGE = "";
    private static final String TARGET_APP_NAME = "XMPermission"; // 应用名称
    private boolean isHandling = false;
    private Handler handler = new Handler(Looper.getMainLooper());
    private int scrollAttempts = 0;
    private static final int MAX_SCROLL_ATTEMPTS = 15;
    private boolean isScrollingUp = false;
    private boolean hasScrolledToBottom = false;
    private static final int SCROLL_DELAY = 300;

    // 修改华为滑动延迟和对话框处理相关常量
    private static final int HUAWEI_SCROLL_DELAY = 500; // 更长的华为滑动间隔，从3500增加到4500

    // 华为相关常量
    private static final String HUAWEI_SETTINGS_PACKAGE = "com.huawei.systemmanager";
    private static final String[] HUAWEI_STARTUP_KEYWORDS = {
            "启动管理", "自动启动", "应用启动", "自启动管理", "开机启动"
    };
    private boolean isHuaweiSettingsHandling = false;
    private boolean isFindStartupManagerMode = false;

    // 小米相关常量
    private static final String XIAOMI_SETTINGS_PACKAGE = "com.miui.securitycenter";
    private static final String CONFIRM_BUTTON_TEXT = "确定";

    private static AutoStartAccessibilityService instance;

    // 标识
    private boolean isInStartupAppControlActivity = false; // 是否在华为启动管理页面
    private boolean hasClickedAppSwitch = false; // 是否点击了开关

    // 静态接口用于接收操作结果
    public interface GestureCallback {
        void onResult(boolean success, String message);
    }

    private static GestureCallback mGestureCallback;

    // 设置手势操作回调
    public static void setGestureCallback(GestureCallback callback) {
        mGestureCallback = callback;
    }

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        instance = this;
        
        // 确保配置包含手势支持
        AccessibilityServiceInfo info = getServiceInfo();
        if (info != null) {
            info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
            info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
            info.notificationTimeout = 100;
            info.flags |= AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE;
            setServiceInfo(info);
        }
        
        Log.i(TAG, "无障碍服务已连接，手势支持已配置");
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (TextUtils.isEmpty(TARGET_APP_PACKAGE)) {
            return; // 如果目标包名为空，直接返回
        }

        // 监听窗口状态变化事件
        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "";
            String className = event.getClassName() != null ? event.getClassName().toString() : "";

            Log.i(TAG, "窗口状态变化: 包名=" + packageName + ", 类名=" + className + ",当前设备=" + AutoStartHelper.getManufacturer());

            if (AutoStartHelper.isHuaweiDevice()) {//是否为huawei
//                if (AutoStartHelper.isHarmonyOS()) {
                hasHuaweiHarmony(packageName, className);
//                }
            } else if (AutoStartHelper.isXiaomiDevice() && XIAOMI_SETTINGS_PACKAGE.equals(packageName) && isHandling) {
                Log.i(TAG, "检测到进入小米安全中心，准备处理自启动设置");
                handler.postDelayed(this::scrollAndSearchMiuiPage, 500);
            } else if (isHandling) {
                handler.postDelayed(this::scrollAndSearchMiuiPage, 500);
            }
        }

//        // 处理华为启动管理页面内容变化
//        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
//            if (isHandling && isHuaweiSettingsHandling) {
//                String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "";
//                if (HUAWEI_SETTINGS_PACKAGE.equals(packageName) && isInStartupAppControlActivity) {
//                    // 增加处理的时间间隔
//                    handler.postDelayed(this::handleHuaweiStartupManager, 1000);
//                }
//            }
//        }
    }

    private void hasHuaweiHarmony(String packageName, String className) {
        // 检测进入系统设置的应用和通知界面
        if ("com.android.settings".equals(packageName) && isFindStartupManagerMode) {
            boolean isAppNotificationDashboard = className.contains("AppAndNotificationDashboardActivity");

            if (isAppNotificationDashboard) {
                Log.i(TAG, "检测到AppAndNotificationDashboardActivity，直接处理无需滚动");

                // 直接处理此界面，不需要等待
                AccessibilityNodeInfo root = getRootInActiveWindow();
                if (root != null) {
                    try {
                        // 直接搜索并点击，无需滚动
                        boolean found = searchHuaweiStartupMenuNoScroll(root);
                    } finally {
                        root.recycle();
                    }
                }

                // 取消任何可能的延迟任务
                handler.removeCallbacksAndMessages(null);
            }
        }

        // 检测对话框
        else if ("android.app.AlertDialog".equals(className)) {
            Log.i(TAG, "检测到对话框");

            Log.i(TAG, "确认是华为自启动设置对话框");

            if (hasClickedAppSwitch) {
                // 取消先前可能的对话框检查任务
                handler.removeCallbacksAndMessages(null);

                // 延迟执行以确保对话框加载完成
                handler.postDelayed(() -> {
                    Log.i(TAG, "准备处理华为确认对话框，给予足够显示时间");
                    handleHuaweiConfirmDialog();
                }, 600); // 增加到2秒
            }
        }// 精确检测进入华为自启动设置页面
        else if ((HUAWEI_SETTINGS_PACKAGE.equals(packageName) || "com.hihonor.systemmanager".equals(packageName)) &&
                className.contains("StartupAppControlActivity")) {
            Log.i(TAG, "检测到进入华为自启动设置页面hasClickedAppSwitch=" + hasClickedAppSwitch);
            isHuaweiSettingsHandling = true;
            isInStartupAppControlActivity = true;
            hasClickedAppSwitch = false;

            // 延迟执行以确保页面加载完成
            handler.postDelayed(this::handleHuaweiStartupManager, 1500); // 增加延迟
        }
    }


    // 在当前页面查找并操作目标应用
    private boolean findAndToggleTargetInCurrentPage(AccessibilityNodeInfo rootNode) {
        // 通过应用名查找
        List<AccessibilityNodeInfo> nodes = rootNode.findAccessibilityNodeInfosByText(TARGET_APP_NAME);
        if (nodes != null && !nodes.isEmpty()) {
            for (AccessibilityNodeInfo node : nodes) {
                if (node != null) {
                    try {
                        // 查找附近的开关
                        AccessibilityNodeInfo switchNode = findNearbySwitchNode(node, rootNode);
                        if (switchNode != null) {
                            try {
                                // 检查开关状态
                                boolean isChecked = switchNode.isChecked();
                                Log.i(TAG, "找到目标应用开关，当前状态: " + (isChecked ? "已开启" : "未开启"));

                                TARGET_APP_PACKAGE = null;
                                // 如果已开启，直接返回
                                handler.postDelayed(() -> returnToAppWithResult(isChecked, (isChecked ? "已开启" : "未开启")), 500);

//                                if (!isChecked) {
//                                    // 如果未开启，点击开关
//                                    boolean clicked = performClick(switchNode);
//                                    Log.i(TAG, "点击自启动开关: " + (clicked ? "成功" : "失败"));
//
//                                    TARGET_APP_PACKAGE = null;
//                                    handler.postDelayed(() -> returnToAppWithResult(true,"成功"), 500);
//                                    // 等待并处理可能的确认对话框
////                                    handler.postDelayed(this::handleConfirmDialog, 1000);
//                                } else {
//                                    TARGET_APP_PACKAGE = null;
//                                    // 如果已开启，直接返回
//                                    handler.postDelayed(() -> returnToAppWithResult(true,"成功"), 500);
//                                }

                                return true;
                            } finally {
                                switchNode.recycle();
                            }
                        }
                    } finally {
                        node.recycle();
                    }
                }
            }
        }

        return false;
    }

    // 小米页面滚动查找
    private void scrollAndSearchMiuiPage() {
        if (!isHandling) return;

        Log.i(TAG, "开始滚动搜索小米页面");

        // 用于重试计数
        final int[] retryCount = {0};
        final int MAX_RETRIES = 2;

        // 定义递归重试函数
        Runnable attemptScrollSearch = new Runnable() {
            @Override
            public void run() {
                AccessibilityNodeInfo rootNode = getRootInActiveWindow();
                if (rootNode == null) {
                    Log.e(TAG, "根节点为空，无法滚动搜索小米页面");
                    if (retryCount[0] < MAX_RETRIES) {
                        retryCount[0]++;
                        Log.i(TAG, "尝试重试 (" + retryCount[0] + "/" + MAX_RETRIES + ")...");
                        handler.postDelayed(this, 2000); // 2秒后重试
                    } else {
                        Log.e(TAG, "重试次数已用尽，返回应用");
                        returnToAppWithResult(false, "重试次数已用尽，返回应用");
                    }
                    return;
                }

                try {
                    // 查找可滚动视图
                    AccessibilityNodeInfo scrollableNode = findScrollableView(rootNode);

                    if (scrollableNode == null) {
                        Log.e(TAG, "未找到可滚动视图");
                        if (retryCount[0] < MAX_RETRIES) {
                            retryCount[0]++;
                            Log.i(TAG, "尝试重试 (" + retryCount[0] + "/" + MAX_RETRIES + ")...");
                            handler.postDelayed(this, 2000); // 2秒后重试
                        } else {
                            Log.e(TAG, "重试次数已用尽，返回应用");
                            returnToAppWithResult(false, "重试次数已用尽，返回应用");
                        }
                        return;
                    }

                    // 查找当前页面中的目标应用
                    boolean foundTarget = findAndToggleTargetInCurrentPage(rootNode);

                    // 如果没找到，开始滚动查找
                    if (foundTarget) {
                        //此处返回uni的状态，为true
                        return;
                    }

                    // 执行滚动操作
                    boolean scrolled = scrollableNode.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
                    scrollableNode.recycle();

                    if (scrolled) {
                        scrollAttempts++;
                        Log.i(TAG, "滚动小米页面成功，尝试次数: " + scrollAttempts);

                        // 延迟后检查当前页面是否有目标应用
                        handler.postDelayed(() -> {
                            AccessibilityNodeInfo newRoot = getRootInActiveWindow();
                            if (newRoot != null) {
                                try {
                                    boolean found = findAndToggleTargetInCurrentPage(newRoot);
                                    if (found) {
                                        Log.i(TAG, "滚动后找到了目标应用");
                                        return;
                                    }

                                    // 如果滚动尝试次数超过最大值，则重置并返回
                                    if (scrollAttempts >= MAX_SCROLL_ATTEMPTS) {
                                        Log.i(TAG, "达到最大滚动次数，停止搜索");
                                        returnToAppWithResult(false, "达到最大滚动次数,停止搜索");
                                        return;
                                    }

                                    // 继续滚动
                                    handler.postDelayed(this, SCROLL_DELAY);
                                } finally {
                                    newRoot.recycle();
                                }
                            }
                        }, SCROLL_DELAY);
                    } else {
                        // 滚动失败，可能到达边界
                        Log.i(TAG, "滚动小米页面失败，可能到达列表底部");
                        returnToAppWithResult(false, "滚动小米页面失败，可能到达列表底部");
                    }
                } finally {
                    rootNode.recycle();
                }
            }
        };

        // 开始第一次尝试
        attemptScrollSearch.run();
    }

    // 改进查找并操作华为页面中的目标应用方法
    private boolean findAndToggleTargetInHuaweiPage(AccessibilityNodeInfo rootNode) {
        List<AccessibilityNodeInfo> nameNodes = rootNode.findAccessibilityNodeInfosByText(TARGET_APP_NAME);
        boolean foundByName = false;

        if (nameNodes != null) {
            Log.i(TAG, "找到包含目标应用名称的节点数量: " + nameNodes.size());
        }

        // 通过应用名查找和处理
        if (nameNodes != null && !nameNodes.isEmpty()) {
            for (AccessibilityNodeInfo node : nameNodes) {
                if (node != null) {
                    try {
                        String nodeText = node.getText() != null ? node.getText().toString() : "";
                        Log.i(TAG, "检查节点文本: " + nodeText);

                        // 确保找到的是完整的应用名而不是部分匹配
                        if (nodeText.contains(TARGET_APP_NAME)) {
                            Log.i(TAG, "找到目标应用: " + nodeText);

                            // 查找附近的开关
                            AccessibilityNodeInfo switchNode = findNearbySwitchNode(node, rootNode);
                            if (switchNode != null) {
                                try {
                                    // 检查开关状态并打印日志
                                    boolean isChecked = switchNode.isChecked();
                                    Log.i(TAG, "找到目标应用开关，当前状态: " + (isChecked ? "已开启" : "未开启"));

                                    // 点击开关
                                    if (!isChecked) {
                                        performClick(switchNode);
                                    }
                                    boolean clicked = performClick(switchNode);
                                    Log.i(TAG, "点击自启动开关: " + (clicked ? "成功" : "失败"));

                                    // 点击后立即返回应用，不等待对话框
                                    Log.i(TAG, "已点击开关，立即返回应用");
                                    hasClickedAppSwitch = true;

                                    foundByName = true;
                                    break;
                                } finally {
                                    switchNode.recycle();
                                }
                            } else {
                                Log.i(TAG, "未找到目标应用的开关节点");
                            }
                        }
                    } finally {
                        node.recycle();
                    }
                }

                if (foundByName) break;
            }
        }

        return foundByName;
    }

    // 添加带结果返回的方法
    private void returnToAppWithResult(boolean result, String tips) {
        Log.i(TAG, "返回应用并带有结果: " + result);

        // 停止所有延迟任务
        handler.removeCallbacksAndMessages(null);

        // 重置所有状态
        resetSearch();

        // 执行返回操作
        // 注释掉返回操作
        Log.i(TAG, "执行返回操作已被注释");

        // 如果还需要额外的返回，可以增加延迟执行的返回操作
        handler.postDelayed(() -> {
            // 此处返回uni的状态为true
            performGlobalAction(GLOBAL_ACTION_BACK);
            PermissionHelper.notifyResult(result, tips);
        }, 500);
    }

    // 修改华为启动管理处理方法，检测到点击后立即终止
    private void handleHuaweiStartupManager() {
        if (!isInStartupAppControlActivity) return;

        Log.i(TAG, "处理华为自启动设置页面");

            AccessibilityNodeInfo rootNode = getRootInActiveWindow();
            if (rootNode == null) return;

        try {
            // 查找并处理目标应用
            boolean found = findAndToggleTargetInHuaweiPage(rootNode);

            // 如果找到并处理了目标应用，就不再执行后续的滚动操作
            if (found) {
                Log.i(TAG, "已找到并处理目标应用，取消后续滚动操作");
                return;
            }

            // 如果未找到目标应用，执行滚动操作
            scrollAndSearchHuaweiPage();
        } finally {
            rootNode.recycle();
        }
    }

    // 修改处理华为确认对话框方法
    private void handleHuaweiConfirmDialog() {
        Log.i(TAG, "处理华为确认对话框");

        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        if (rootNode == null) {
            returnToAppWithResult(false, "无法获取当前窗口，对话框处理失败");
            Log.e(TAG, "无法获取当前窗口，对话框处理失败");
                            return;
                        }

        try {
            // 查找对话框中的所有开关
            List<AccessibilityNodeInfo> switchNodes = findAllSwitchNodes(rootNode);

            // 检查开关数量并记录状态
            boolean allEnabled;

            if (switchNodes.size() > 0) {
                Log.i(TAG, "找到对话框中的开关数量: " + switchNodes.size());
                allEnabled = checkAllSwitchStatus(switchNodes);
                Log.i(TAG, "华为自启动权限状态检查结果: " + (allEnabled ? "true" : "false"));
            } else {
                allEnabled = false;
                Log.i(TAG, "对话框中未找到开关，返回false");
            }
            TARGET_APP_PACKAGE = null;
            hasClickedAppSwitch = false;

            returnToAppWithResult(allEnabled, "成功");
        } finally {
            rootNode.recycle();
        }
    }

    // 修改检查开关状态方法
    private boolean checkAllSwitchStatus(List<AccessibilityNodeInfo> switchNodes) {
        boolean allEnabled = true;
        int enabledCount = 0;
        StringBuilder switchStatus = new StringBuilder("开关状态: ");

        // 检查每个开关的状态
        for (int i = 0; i < switchNodes.size(); i++) {
            AccessibilityNodeInfo switchNode = switchNodes.get(i);
            if (switchNode != null) {
                try {
                    boolean isChecked = switchNode.isChecked();
                    switchStatus.append("[").append(i).append("]=").append(isChecked ? "开启" : "关闭").append(" ");

                    if (!isChecked) {
                        allEnabled = false;
                    } else {
                        enabledCount++;
                    }
                } finally {
                    switchNode.recycle();
                }
            }
        }

        Log.i(TAG, switchStatus.toString());
        Log.i(TAG, "已开启开关数量: " + enabledCount + "/" + switchNodes.size());

        return allEnabled; // 返回是否所有开关都已启用
    }

    // 华为页面滚动查找
    private void scrollAndSearchHuaweiPage() {
        Log.i(TAG, "开始滚动搜索华为页面");

        // 用于重试计数
        final int[] retryCount = {0};
        final int MAX_RETRIES = 2;

        // 定义递归重试函数
        Runnable attemptScrollSearch = new Runnable() {
            @Override
            public void run() {
                AccessibilityNodeInfo rootNode = getRootInActiveWindow();
                if (rootNode == null) {
                    Log.e(TAG, "根节点为空，无法滚动搜索华为页面");
                    if (retryCount[0] < MAX_RETRIES) {
                        retryCount[0]++;
                        Log.i(TAG, "尝试重试 (" + retryCount[0] + "/" + MAX_RETRIES + ")...");
                        handler.postDelayed(this, 2000); // 2秒后重试
                    } else {
                        Log.e(TAG, "重试次数已用尽，返回应用");
                        returnToAppWithResult(false, "重试次数已用尽，返回应用");
                    }
                    return;
                }

                try {
                    // 查找可滚动视图
                    AccessibilityNodeInfo scrollableNode = findScrollableView(rootNode);

                    if (scrollableNode == null) {
                        Log.e(TAG, "未找到可滚动视图");
                        if (retryCount[0] < MAX_RETRIES) {
                            retryCount[0]++;
                            Log.i(TAG, "尝试重试 (" + retryCount[0] + "/" + MAX_RETRIES + ")...");
                            handler.postDelayed(this, 2000); // 2秒后重试
                        } else {
                            Log.e(TAG, "重试次数已用尽，返回应用");
                            returnToAppWithResult(false, "重试次数已用尽，返回应用");
                        }
                        return;
                    }

                    // 执行滚动操作
                    boolean scrolled = scrollableNode.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
                    scrollableNode.recycle();

                    if (scrolled) {
                        scrollAttempts++;
                        Log.i(TAG, "滚动华为页面成功，尝试次数: " + scrollAttempts);

                        // 延迟后检查当前页面是否有目标应用
                        handler.postDelayed(() -> {
                            AccessibilityNodeInfo newRoot = getRootInActiveWindow();
                            if (newRoot != null) {
                                try {
                                    boolean found = findAndToggleTargetInHuaweiPage(newRoot);
                                    if (found) {
                                        Log.i(TAG, "滚动后找到了目标应用");
                                        return;
                                    }

                                    // 如果滚动尝试次数超过最大值，则重置并返回
                                    if (scrollAttempts >= MAX_SCROLL_ATTEMPTS) {
                                        Log.i(TAG, "达到最大滚动次数，停止搜索");
                                        returnToAppWithResult(false, "达到最大滚动次数，停止搜索");
                                        resetAndStartHandling();
                                    return;
                                    }

                                    // 继续滚动
                                    handler.postDelayed(this, HUAWEI_SCROLL_DELAY);
                                } finally {
                                    newRoot.recycle();
                                }
                            }
                        }, SCROLL_DELAY);
                    } else {
                        // 滚动失败，可能到达边界
                        Log.i(TAG, "滚动华为页面失败，可能到达列表底部");
                        // 清理搜索状态
                        returnToAppWithResult(false, "滚动华为页面失败，可能到达列表底部");
                        resetAndStartHandling();
                    }
                } finally {
                    rootNode.recycle();
                }
            }
        };

        // 开始第一次尝试
        attemptScrollSearch.run();
    }

    // 查找节点附近的开关
    private AccessibilityNodeInfo findNearbySwitchNode(AccessibilityNodeInfo targetNode, AccessibilityNodeInfo rootNode) {
        if (targetNode == null || rootNode == null) return null;

        // 获取目标节点位置
        Rect targetRect = new Rect();
        targetNode.getBoundsInScreen(targetRect);

        // 查找所有开关节点
        List<AccessibilityNodeInfo> switchNodes = findAllSwitchNodes(rootNode);

        // 查找离目标节点最近的开关
        AccessibilityNodeInfo nearestSwitch = null;
        int minDistance = Integer.MAX_VALUE;

        for (AccessibilityNodeInfo switchNode : switchNodes) {
            Rect switchRect = new Rect();
            switchNode.getBoundsInScreen(switchRect);

            // 计算距离（简单使用X轴距离）
            int distance = Math.abs(switchRect.left - targetRect.right);
            if (Math.abs(switchRect.centerY() - targetRect.centerY()) < 100 && distance < minDistance) {
                minDistance = distance;
                nearestSwitch = switchNode;
            }
        }

        return nearestSwitch;
    }

    // 查找所有开关节点
    private List<AccessibilityNodeInfo> findAllSwitchNodes(AccessibilityNodeInfo rootNode) {
        List<AccessibilityNodeInfo> result = new java.util.ArrayList<>();
        if (rootNode == null) return result;

        // 递归查找开关类型节点
        findSwitchNodesRecursive(rootNode, result);

        return result;
    }

    // 递归查找开关节点
    private void findSwitchNodesRecursive(AccessibilityNodeInfo node, List<AccessibilityNodeInfo> result) {
        if (node == null) return;

        // 检查是否是开关类型
        CharSequence className = node.getClassName();
        if (className != null && (
                "android.widget.Switch".equals(className) ||
                        "android.widget.ToggleButton".equals(className) ||
                        "android.widget.CheckBox".equals(className))) {
            result.add(AccessibilityNodeInfo.obtain(node));
        }

        // 遍历子节点
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo child = node.getChild(i);
            if (child != null) {
                findSwitchNodesRecursive(child, result);
                child.recycle();
            }
        }
    }

    // 查找可滚动视图
    private AccessibilityNodeInfo findScrollableView(AccessibilityNodeInfo rootNode) {
        if (rootNode == null) return null;

        // 如果根节点可滚动，直接返回
        if (rootNode.isScrollable()) {
            return AccessibilityNodeInfo.obtain(rootNode);
        }

        // 查找可滚动的子节点
        for (int i = 0; i < rootNode.getChildCount(); i++) {
            AccessibilityNodeInfo child = rootNode.getChild(i);
            if (child != null) {
                try {
                    if (child.isScrollable()) {
                        return AccessibilityNodeInfo.obtain(child);
                    }

                    // 递归查找
                    AccessibilityNodeInfo scrollable = findScrollableView(child);
                    if (scrollable != null) {
                        return scrollable;
                    }
                } finally {
                    child.recycle();
                }
            }
        }

        return null;
    }

    // 查找可点击的父节点
    private AccessibilityNodeInfo findClickableParent(AccessibilityNodeInfo node) {
        if (node == null) return null;

        // 如果自身可点击，直接返回副本
        if (node.isClickable()) {
            return AccessibilityNodeInfo.obtain(node);
        }

        // 否则递归查找父节点
        AccessibilityNodeInfo parent = node.getParent();
        if (parent == null) return null;

        try {
            if (parent.isClickable()) {
                return AccessibilityNodeInfo.obtain(parent);
            } else {
                AccessibilityNodeInfo clickableParent = findClickableParent(parent);
                return clickableParent;
            }
        } finally {
            parent.recycle();
        }
    }

    // 执行点击操作
    private boolean performClick(AccessibilityNodeInfo node) {
        if (node == null) return false;
        return node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
    }

    // 返回应用
    private void returnToApp() {
        // 停止所有延迟任务
        handler.removeCallbacksAndMessages(null);

        // 重置所有状态
        resetSearch();

        // 执行返回操作
        // 注释掉返回操作
        Log.i(TAG, "执行返回操作已被注释");

        // 如果还需要额外的返回，可以增加延迟执行的返回操作
        handler.postDelayed(() -> {
            //此处返回uni的状态为true
            // 注释掉返回操作
            performGlobalAction(GLOBAL_ACTION_BACK);
        }, 500);
    }

    // 重置搜索状态
    private void resetSearch() {
        scrollAttempts = 0;
        hasScrolledToBottom = false;
        isScrollingUp = false;
        isHandling = false;
        isHuaweiSettingsHandling = false;
        isFindStartupManagerMode = false;
        isInStartupAppControlActivity = false;
        Log.i(TAG, "重置搜索状态");
    }

    // 只重置服务状态的方法，不执行返回操作
    private void resetServiceOnly() {
        // 停止所有延迟任务
        handler.removeCallbacksAndMessages(null);

        // 重置所有状态变量
        scrollAttempts = 0;
        hasScrolledToBottom = false;
        isScrollingUp = false;
        isHandling = false;
        isHuaweiSettingsHandling = false;
        isFindStartupManagerMode = false;
        isInStartupAppControlActivity = false;

        Log.i(TAG, "已重置服务状态，停留在当前页面");
    }

    // 设置目标应用包名
    public static void setTargetPackage(String packageName) {
        TARGET_APP_PACKAGE = packageName;
    }

    // 启动处理
    public static void resetAndStartHandling() {
        if (instance != null) {
            instance.resetSearch();
            instance.startHandling();
        }
    }

    // 启动处理
    private void startHandling() {
        isHandling = true;
    }

    // 启动查找启动管理模式
    public static void startFindStartupManager() {
        if (instance != null) {
            instance.resetSearch();
            instance.isFindStartupManagerMode = true;
            instance.isHandling = true;
            Log.i(TAG, "启动查找启动管理模式");
        }
    }

    @Override
    public void onInterrupt() {
        Log.i(TAG, "无障碍服务中断");
    }

    // 检测设备是否有导航栏
    private boolean hasNavigationBar() {
        // 简单实现，实际中可能需要更复杂的检测方法
        return true; // 假设设备有导航栏
    }

    // 直接启动目标应用
    private void launchTargetApp() {
        try {
            // 直接启动 MainActivity
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 确保在新任务中启动
            startActivity(intent);
            Log.i(TAG, "成功启动应用的主界面: " + MainActivity.class.getName());
        } catch (Exception e) {
            Log.e(TAG, "启动应用失败", e);
        }
    }

    // 添加专门针对AppNotificationDashboard的无滚动检索方法
    private boolean searchHuaweiStartupMenuNoScroll(AccessibilityNodeInfo rootNode) {
        if (rootNode == null) return false;

        boolean found = false;
        Log.i(TAG, "在AppAndNotificationDashboard中直接检索启动管理选项");

        // 通过关键词查找启动管理入口
        for (String keyword : HUAWEI_STARTUP_KEYWORDS) {
            List<AccessibilityNodeInfo> nodes = rootNode.findAccessibilityNodeInfosByText(keyword);
            if (nodes != null && !nodes.isEmpty()) {
                for (int i = 0; i < nodes.size(); i++) {
                    AccessibilityNodeInfo node = nodes.get(i);
                    if (node != null) {
                        try {
                            // 找到节点或其父节点的可点击元素
                            AccessibilityNodeInfo clickableNode = findClickableParent(node);
                            if (clickableNode != null) {
                                try {
                                    boolean clicked = performClick(clickableNode);
                                    Log.i(TAG, "点击启动管理选项: " + keyword + (clicked ? " 成功" : " 失败"));

                                    if (clicked) {
                                        found = true;
                                        isHuaweiSettingsHandling = true;
                                        isFindStartupManagerMode = false;

                                        // 记录日志但不执行返回，外部已设置延迟返回
                                        Log.i(TAG, "成功点击选项，稍后将关闭设置界面");
                                        break;
                                    }
                                } finally {
                                    clickableNode.recycle();
                                }
                            }
                        } finally {
                            node.recycle();
                        }
                    }
                }
                if (found) break;
            }
        }

        if (!found) {
            Log.i(TAG, "AppAndNotificationDashboard中未找到启动管理选项");
        }

        return found;
    }

    // 执行单点点击操作
    public boolean performClick(float x, float y) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            if (mGestureCallback != null) {
                mGestureCallback.onResult(false, "设备Android版本过低，不支持该操作");
            }
            return false;
        }

        // 创建点击手势
        Path clickPath = new Path();
        clickPath.moveTo(x, y);

        GestureDescription.StrokeDescription clickStroke =
                new GestureDescription.StrokeDescription(clickPath, 0, 100);

        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
        gestureBuilder.addStroke(clickStroke);

        return dispatchGesture(gestureBuilder.build(), new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                Log.i(TAG, "点击坐标 (" + x + ", " + y + ") 成功");
                if (mGestureCallback != null) {
                    handler.post(() -> mGestureCallback.onResult(true, "点击成功"));
                }
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                Log.e(TAG, "点击坐标 (" + x + ", " + y + ") 被取消");
                if (mGestureCallback != null) {
                    handler.post(() -> mGestureCallback.onResult(false, "点击被取消"));
                }
            }
        }, null);
    }

    // 执行滑动操作
    public boolean performSwipe(float x1, float y1, float x2, float y2) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            if (mGestureCallback != null) {
                mGestureCallback.onResult(false, "设备Android版本过低，不支持该操作");
            }
            return false;
        }

        // 创建滑动路径
        Path swipePath = new Path();
        swipePath.moveTo(x1, y1);
        swipePath.lineTo(x2, y2);

        // 滑动时间设为500ms
        GestureDescription.StrokeDescription swipeStroke =
                new GestureDescription.StrokeDescription(swipePath, 0, 500);

        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
        gestureBuilder.addStroke(swipeStroke);

        return dispatchGesture(gestureBuilder.build(), new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                Log.i(TAG, "滑动从 (" + x1 + ", " + y1 + ") 到 (" + x2 + ", " + y2 + ") 成功");
                if (mGestureCallback != null) {
                    handler.post(() -> mGestureCallback.onResult(true, "滑动成功"));
                }
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                Log.e(TAG, "滑动从 (" + x1 + ", " + y1 + ") 到 (" + x2 + ", " + y2 + ") 被取消");
                if (mGestureCallback != null) {
                    handler.post(() -> mGestureCallback.onResult(false, "滑动被取消"));
                }
            }
        }, null);
    }

    // 提供静态获取实例的方法
    public static AutoStartAccessibilityService getInstance() {
        return instance;
    }

    // 添加重写方法，确保手势操作功能可用
    @Override
    public void onDestroy() {
        instance = null;
        super.onDestroy();
    }

    /**
     * 执行点击操作 - 供内部调用
     */
    public boolean performClickGesture(float x, float y, AccessibilityService.GestureResultCallback callback) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            return false;
        }

        Path clickPath = new Path();
        clickPath.moveTo(x, y);
        
        GestureDescription.StrokeDescription clickStroke = 
                new GestureDescription.StrokeDescription(clickPath, 0, 100);
        
        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
        gestureBuilder.addStroke(clickStroke);
        
        return dispatchGesture(gestureBuilder.build(), callback, null);
    }

    /**
     * 执行滑动操作 - 供内部调用
     */
    public boolean performSwipeGesture(float x1, float y1, float x2, float y2, AccessibilityService.GestureResultCallback callback) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            return false;
        }

        Path swipePath = new Path();
        swipePath.moveTo(x1, y1);
        swipePath.lineTo(x2, y2);
        
        GestureDescription.StrokeDescription swipeStroke = 
                new GestureDescription.StrokeDescription(swipePath, 0, 500);
        
        GestureDescription.Builder gestureBuilder = new GestureDescription.Builder();
        gestureBuilder.addStroke(swipeStroke);
        
        return dispatchGesture(gestureBuilder.build(), callback, null);
    }
}